package P122_ThreadException;
import org.junit.Test;

/**
 * 使用线程异常处理器提升系统可靠性
 * @author xufy1
 */
public class ThreadException {


    @Test
    public void test1() {
        new TcpServer().threadStart();
    }

    public static void main(String[] args) {
        new TcpServer().threadStart();
    }
}
class TcpServer implements Runnable {

    public void threadStart() {
        Thread t = new Thread(this);
        t.setUncaughtExceptionHandler(new TcpServerExceptionHandler());
        t.setPriority(Thread.MAX_PRIORITY);
        t.start();
    }


    @Override
    public void run() {
        for (int i = 0; i < 3; i++) {
            try {
                //在单元测试中，如果子线程处于阻塞、死亡状态时，单元测试会立刻停止所有子线程，同时退出程序！
                Thread.sleep(1000);
                System.out.println("系统正常运行："+i);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        throw new RuntimeException();
    }
}
class TcpServerExceptionHandler implements Thread.UncaughtExceptionHandler {

    public void uncaughtException(Thread t, Throwable e) {
        //记录线程异常信息
        System.out.println("线程 " + t.getName() + "出现异常，自行重启，请分析原因。");
        e.printStackTrace();
        //重启线程，保证业务不中断
        new TcpServer().threadStart();
    }
}